using Digitalmes.Domain.Entities.Mes.Masters;
using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.Operations.Queries;

/// <summary>
/// 工序分页查询命令。
/// </summary>
public record GetOperationListWithPagedQuery(
    long LineId,
    int PageNumber,
    int PageSize) : IPagedQuery, IRequest<IResult<PagedList<ProcOperationDto>>>;

internal sealed class GetOperationListWithPagedQueryHandler(IRepository<ProcOperation> repo, IRepository<MdWorkstation> repo2) : IRequestHandler<GetOperationListWithPagedQuery, IResult<PagedList<ProcOperationDto>>>
{
    public async Task<IResult<PagedList<ProcOperationDto>>> Handle(GetOperationListWithPagedQuery request, CancellationToken cancellationToken)
    {
        // 分页查询后再单独查询，查看是否有更简化的方法
        var items = await repo.GetPagedListAsync(m => m.LineId == request.LineId, request.PageNumber, request.PageSize, cancellationToken);
        if (items.Total > 0)
        {
            var wsIds = items.Items.SelectMany(m => m.WsIds).Distinct().ToArray();
            var workstations = await repo2.GetListAsync(m => wsIds.Contains(m.Id), cancellationToken);
            foreach (var item in items.Items)
            {
                item.Workstations = workstations.Where(s => item.WsIds.Contains(s.Id)).ToArray();
            }
        }

        return Result.From(items.Adapt<PagedList<ProcOperationDto>>());
    }
}

